package com.qiangesoft.rabbitmq.consumer;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 消息消费失败配置
 * ps：配置处理失败消息的交换机和队列
 *
 * @author qiangesoft
 * @date 2024-05-08
 */
@Configuration
public class ErrorMessageConfig {

    public static final String EXCHANGE = "error.exchange";

    public static final String QUEUE = "error.queue";

    public static final String ROUTING_KEY = "error";

    @Bean
    public DirectExchange errorMessageExchange() {
        return new DirectExchange(EXCHANGE);
    }

    @Bean
    public Queue errorQueue() {
        return new Queue(QUEUE, true);
    }

    @Bean
    public Binding errorBinding(Queue errorQueue, DirectExchange errorMessageExchange) {
        return BindingBuilder.bind(errorQueue).to(errorMessageExchange).with(ROUTING_KEY);
    }

    @Bean
    public MessageRecoverer republishMessageRecoverer(RabbitTemplate rabbitTemplate) {
        return new RepublishMessageRecoverer(rabbitTemplate, EXCHANGE, ROUTING_KEY);
    }

}
